package logic

import (
	"context"

	"book/common/errorx"
	"book/service/sstwords/cmd/api/internal/svc"
	"book/service/sstwords/cmd/api/internal/types"
	"book/service/sstwords/cmd/rpc/sstwords"
	"book/service/user/cmd/rpc/userclient"

	"github.com/tal-tech/go-zero/core/logx"
	"github.com/tal-tech/go-zero/core/mr"
)

type SstwordsFilterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSstwordsFilterLogic(ctx context.Context, svcCtx *svc.ServiceContext) SstwordsFilterLogic {
	return SstwordsFilterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SstwordsFilterLogic) SstwordsFilter(req types.SstwordsFilterReq) (resp interface{}, err error) {

	// 调用多个rpc服务 实例
	var sstwords_resp types.SstwordsFilterResp
	err = mr.Finish(func() (err error) {
		var userId int64 = 1 // todo debug 用户ID

		// 调用user.rpc服务
		userInfo, err := l.svcCtx.UserRpc.GetUser(l.ctx, &userclient.IdReq{
			Id: userId,
		})
		sstwords_resp.User = userInfo
		return
	}, func() (err error) {
		// 调用sstwords.rpc服务
		res, err := l.svcCtx.SstwordsRpc.FilterSstwords(l.ctx, &sstwords.FilterSstwordsRequest{
			Keywords: req.Keywords,
			Mask:     req.Mask,
		})
		sstwords_resp.Safeword = res.SafeWord
		sstwords_resp.Keywords = res.Keywords
		sstwords_resp.Found = res.Found
		return
	})

	if err != nil {
		return errorx.NewDefaultError(err.Error()), nil
	}

	return errorx.NewCodeSuccess(&sstwords_resp, "success"), nil
}
